package com.test.test11;

import android.content.Context;
import android.content.pm.PackageManager;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkInfo;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.telephony.TelephonyManager;
import android.util.Log;


import java.math.BigInteger;
import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static android.content.Context.CONNECTIVITY_SERVICE;

/**
 * 通用的一些工具类
 */
public class CommonUtils {

    private static final String TAG = "COMMON_UTILS";

    // MD5算法名称
    private static final String MD5 = "MD5";
    // 字符串编码
    private static final String ENCODING = "UTF-8";


    /**
     * 动态权限请求
     *
     * @param activity   请求活动
     * @param permission 权限字符串
     */
    @RequiresApi(api = Build.VERSION_CODES.M)
    public static void requestPermission(AppCompatActivity activity, String permission) {
        if (activity.checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) {
            activity.requestPermissions(new String[]{permission}, 0);
        }
    }

    /**
     * 获取网络状态
     *
     * @param context
     * @return 0-没有网络， 1-WiFI网络， 2-2G网络， 3-3G网络， 4-4G网络
     */
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public static int networkAvailable(Context context) {
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(CONNECTIVITY_SERVICE);
        if (connectivityManager != null) {
            Network[] networks = new Network[0];
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
                networks = connectivityManager.getAllNetworks();
            }
            if (networks == null || networks.length == 0) {
                return 0;
            }
            Log.i(TAG, "找到的连接数量：" + networks.length);
            for (Network network : networks) {
                NetworkInfo networkInfo = connectivityManager.getNetworkInfo(network);
                if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
                    return 1;
                } else if (networkInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
                    int subType = networkInfo.getSubtype();
                    TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
                    // 3G 联通的3G为UMTS或HSDPA，电信的3G为EVDO
                    if (subType == TelephonyManager.NETWORK_TYPE_LTE && !telephonyManager.isNetworkRoaming()) {// 4G网络
                        return 4;
                    } else if (subType == TelephonyManager.NETWORK_TYPE_UMTS || subType == TelephonyManager.NETWORK_TYPE_HSDPA || subType == TelephonyManager.NETWORK_TYPE_EVDO_0 && !telephonyManager.isNetworkRoaming()) {
                        return 3;
                    } else if (subType == TelephonyManager.NETWORK_TYPE_GPRS || subType == TelephonyManager.NETWORK_TYPE_EDGE || subType == TelephonyManager.NETWORK_TYPE_CDMA && !telephonyManager.isNetworkRoaming()) {
                        return 2;
                    } else {
                        return 2;
                    }
                }
            }
        }
        return 0;
    }

    /**
     * 判断GPS是否打开
     *
     * @param context
     * @return
     */
    public static boolean isGPSEnabled(Context context) {
        LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
    }

    /**
     * 计算字符串的MD5值
     * @param s 字符串
     * @return
     */
    public static String calMD5(String s) {
        byte[] bytes = s.getBytes(Charset.forName(ENCODING));
        try {
            MessageDigest messageDigest = MessageDigest.getInstance(MD5);
            messageDigest.update(bytes);
            BigInteger result = new BigInteger(1, messageDigest.digest());
            // 将结果以16进制返回
            return result.toString(16);
        } catch (NoSuchAlgorithmException e) {// 正常情况下，该处异常不应该发生，所以此处基本上可以忽略
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 判断一个字符串是不是手机号
     * @param s
     * @return
     */
    public static boolean isPhoneNumber(String s) {
        String regxPn = "^((13[0-9])|(15[^4])|(18[0,2,3,5-9])|(17[0-8])|(147))\\d{8}$";
        Pattern pattern = Pattern.compile(regxPn);
        Matcher matcher = pattern.matcher(s);
        return matcher.matches();
    }

}
